#!/usr/bin/env python
# _*_ coding:utf-8 _*_
#
# Copyright(c) http://m.ecpark.cn/
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import argparse
import sys
import os
import logging
from multiprocessing import Pool

basedir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, basedir)

try:
    from mysql_backup_option import backup_exec_log_path
except Exception as e:
    from mysql_backup_option import backup_exec_log_path

try:
    parser = argparse.ArgumentParser(description='mysql backup command line .',
                                     usage=None,
                                     add_help=True)
    parser.add_argument('--port',
                        '-p',
                        type=int,
                        help='数据库实例端口',
                        required=False)
    args = parser.parse_args()
    port = args.port

except Exception as e:
    print(str(e))

log = logging.getLogger(__name__)
log_file = '{backup_exec_log_path}/mysql_backup.log'.format(
    backup_exec_log_path=backup_exec_log_path)
logging.basicConfig(
    # filename=log_file,
    level=logging.INFO,
    format=
    '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    datefmt='%a, %d %b %Y %H:%M:%S')
logging.getLogger("pika").propagate = False

try:
    from backup_execute import mysql_backup_function
except ImportError as e:
    from backup_execute import mysql_backup_function

    log.exception(str(e))


def main():
    parser.add_argument('--host', type=str, help='数据库主机IP', required=False)
    parser.add_argument('--backup_user',
                        '-u',
                        type=str,
                        help='数据库备份用户',
                        default='backup_user',
                        required=False)
    parser.add_argument('--backup_password',
                        '-a',
                        type=str,
                        help='数据库备份密码',
                        required=False)
    parser.add_argument('--backup_base_dir',
                        '-b',
                        default="/data/mysqlbackup",
                        type=str,
                        help='数据库备份基础目录',
                        required=False)
    parser.add_argument('--mysql_base_path',
                        '-t',
                        type=str,
                        help='mysql数据库基础安装目录',
                        default='/opt/mysql',
                        required=False)

    parser.add_argument('--compress_stream',
                        '-s',
                        type=str,
                        help='备份方式',
                        choices=["tar", "xb", "dump"],
                        required=False)

    parser.add_argument('--version',
                        '-v',
                        action='version',
                        version='version 1.0',
                        help='输出脚本版本信息并退出')

    args = parser.parse_args()

    host = args.host
    port = args.port
    if host is not None and port is not None:
        backup_user = args.backup_user
        backup_password = args.backup_password
        backup_base_dir = args.backup_base_dir
        mysql_base_path = args.mysql_base_path
        compress_stream = args.compress_stream
    else:
        try:
            config_option = __import__('mysql_backup_option')
            instance_config_list = config_option.mysql_instance_backup_config_string
            log.info(
                'Argument not pass from the command line and we will get argument from the config file. '
            )

            try:
                ftwrl_wait_timeout = config_option.ftwrl_wait_timeout
                ftwrl_wait_threshold = config_option.ftwrl_wait_threshold
            except Exception as e:
                ftwrl_wait_timeout = 0
                ftwrl_wait_threshold = 60
            backup_user = config_option.backup_user
            # backup_password = config_option.backup_password
            backup_base_dir = config_option.backup_base_dir
            mysql_base_path = config_option.mysql_base_path
            mysql_backup_process = config_option.mysql_backup_process
            backup_process = Pool(mysql_backup_process)
            try:
                for instance_config in instance_config_list:
                    log.info(instance_config)
                    host = instance_config.get('private_ip')
                    port = instance_config.get('port')
                    compress_stream = instance_config.get('stream_mod')
                    backup_password = instance_config.get('backup_password')
                    # mysql_backup_function(host=host,
                    #                       port=port,
                    #                       backup_user=backup_user,
                    #                       backup_password=backup_password,
                    #                       backup_base_dir=backup_base_dir,
                    #                       mysql_base_path=mysql_base_path,
                    #                       compress_stream=compress_stream)
                    argument = {"host": host, "port": port,
                                "backup_user": backup_user,
                                "backup_password": backup_password,
                                "backup_base_dir": backup_base_dir,
                                "mysql_base_path": mysql_base_path,
                                "compress_stream": compress_stream,
                                "ftwrl_wait_timeout": ftwrl_wait_timeout,
                                "ftwrl_wait_threshold": ftwrl_wait_threshold}
                    backup_process.apply_async(mysql_backup_function, kwds=argument)
                backup_process.close()
                backup_process.join()
            except Exception as e:
                log.error(str(e))

        except ImportError as e:
            log.exception("Can not load config file options , and now exit")
            return 1


if __name__ == "__main__":
    sys.exit(main())
